/*
 * @Author: aim-leo
 * @Date: 2019-03-07 11:57:15
 * @Last Modified by: aim-leo
 * @Last Modified time: 2019-07-29 11:50:01
 */

const Util = require('../util')
const md5 = require('md5')

class Target extends Util {
  constructor(model) {
    super()
    this.model = model
  }

  query({
    params: { page, limit, all } = {
      page: null,
      limit: null
    },
    populate = [],
    filters = {},
    select = {},
    sort
  } = {}) {
    if (all === '1' || all === 1) {
      limit = null
      page = null
    }
    return this.model
      .query(filters, select)
      .populate(populate)
      .limit(limit)
      .skip((page - 1) * limit)
      .sort(sort || { createTime: -1 })
  }

  queryOne({ populate = [], filters = {}, select = {} }) {
    return this.model.queryOne(filters, select).populate(populate)
  }

  count({ filters }) {
    return this.model.count(filters)
  }

  queryById(id, { populate = [], select = {} } = {}) {
    try {
      return this.model.queryById(id).populate(populate).select(select)
    } catch (e) {
      return null
    }
  }

  insert(params) {
    if (params.pwd) {
      params.pwd = md5(params.pwd)
    }
    return this.model.insertOne(params)
  }

  deleteById({ id }) {
    return this.model.delete({
      _id: id
    })
  }

  update(params, filter) {
    return this.model.updateOne(params, filter)
  }

  checkById(id) {
    if (!id) {
      return Promise.reject(new Error('[checkById] id is empty!'))
    }
    return this.model.exsist({ _id: id })
  }
}

module.exports = Target
